<!--
 * @Author: lihaogn
 * @Date: 2022-05-17 15:44:56
 * @LastEditTime: 2022-05-17 23:46:29
 * @LastEditor: lihaogn
 * @Description: 
 * @FilePath: \lix-vue2-demos\src\views\demo\apply\file-visit\modules\DragFile.vue
-->
<template>
  <el-card>
    <div slot="header" class="clearfix">
      <span>使用拖放来选择文件</span>
      <el-button
        v-show="showBtn"
        style="float: right; padding: 0"
        type="text"
        @click="reSelect"
        >重新选择</el-button
      >
    </div>
    <div>
      <div
        class="dropbox"
        v-show="!showBtn"
        @dragenter="handleDragenter"
        @dragover="handleDragover"
        @drop="handleDrop"
      >
        拖拽文件到此
      </div>
      <pre>{{ filesInfoStr }}</pre>
    </div>
  </el-card>
</template>

<script>
import { unitTranform } from '@/utils/common'
export default {
  data() {
    return {
      filesInfoStr: '',
      showBtn: false
    }
  },
  methods: {
    /**
     * @author: lihaogn
     * @Date: 2022-05-17 20:54:13
     * @description: 重新选择
     * @return {*}
     */

    reSelect() {
      this.showBtn = !this.showBtn
      this.filesInfoStr = ''
    },
    /**
     * @author: lihaogn
     * @Date: 2022-05-17 20:42:08
     * @description: 文件处理
     * @param undefined
     * @return {*}
     */

    handleFiles(files) {
      let str = ''
      for (let i = 0; i < files.length; i++) {
        str +=
          'name: ' +
          files[i].name +
          ', size: ' +
          unitTranform(files[i].size) +
          '\r\n'
      }
      this.filesInfoStr = str
    },
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()

      this.showBtn = true

      let dt = e.dataTransfer
      let files = dt.files

      this.handleFiles(files)
    },

    handleDragenter(e) {
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
    }
  }
}
</script>

<style lang="less" scoped>
.dropbox {
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  color: #999;
  border: 2px dotted #ccc;
}
</style>
